<!-- 
    文件上传
    
    注：
      基于el-upload组件，没有分片上传等功能。
      请勿滥用，目前只是为了解决点击上传后，文件显示于qm-upload列表内的场景。

    用法：
      <file-upload
        :bizType="scope.row.name"
        :fileType="scope.row.fileType"
        :fileSize="scope.row.fileSize"
        :dataKey="dataKey || 'qm-uploader-temp-data-key'"
        :ref="scope.row.uploaderRef"
        :fileList="scope.row.files"
      ></file-upload>
 -->
<template>
  <div class="upload-file">
    <el-upload
      ref="uploadRef"
      v-bind="finalUploadOptions"
      :http-request="customUploadRequest"
    >
      <el-button size="mini" type="primary">上传</el-button>
    </el-upload>
  </div>
</template>

<script>
import request from "@/utils/request";
import { Loading } from "element-ui";
import _ from "lodash";

export default {
  name: "file-upload",
  props: {
    // 大小限制(MB)
    fileSize: {
      type: Number,
    },
    // 文件类型, 多个用英文逗号隔开
    fileType: {
      type: String,
    },
    dataKey: {
      type: String,
    },
    bizType: String,
    type: {
      type: String,
      default: "attach",
    },
    // element ui 上传组件属性，请参考：https://element.eleme.cn/#/zh-CN/component/upload
    uploadOptions: {
      type: Object,
      default: () => {},
    },
    fileList: {
      type: Array,
      default: () => [],
    },
    uploadUrl: {
      type: String,
      default: "/attachment/upload",
    },
    showLoading: {
      type: Boolean,
      default: true,
    },
    /**
     * loading关闭是使用loading.close()进行处理的，
     * 如果注入loadingFunc函数，需要返回loading实例，且该示例含close方法。
     */
    loadingFunc: {
      type: Function,
    },
    loadingText: {
      type: String,
      default: "上传中...",
    },
  },
  computed: {
    finalUploadOptions() {
      return _.extend(
        {
          action: "",
          showFileList: false,
          fileList: [],
          multiple: false,
        },
        this.uploadOptions,
        {
          // 这边使用http-request方式上传，需要开启autoUpload
          autoUpload: true,
        }
      );
    },
    isTemp() {
      return this.dataKey === "qm-uploader-temp-data-key";
    },
  },
  methods: {
    // 上传前校检：校验格式、大小
    beforeUploadVerify(file) {
      const fileType = this.fileType;
      const fileSize = this.fileSize;
      if (fileType) {
        const isAllowType =
          fileType.indexOf(
            file.name.toLowerCase().substring(file.name.lastIndexOf(".") + 1)
          ) !== -1;
        if (!isAllowType) {
          this.$message.error("上传文件只能是 " + fileType + " 格式!");
          return false;
        }
      }
      if (fileSize) {
        const isAllowSize = file.size / 1024 / 1024 < fileSize;
        if (!isAllowSize) {
          this.$message.error("上传文件大小不能超过 " + fileSize + "MB!");
          return false;
        }
      }
      return true;
    },
    customUploadRequest(uploadReqData) {
      const { file } = uploadReqData;
      if (!this.beforeUploadVerify(file)) {
        return;
      }
      let loading;
      if (this.showLoading) {
        if (this.loadingFunc) {
          loading = this.loadingFunc();
        } else {
          loading = Loading.service({
            text: this.loadingText,
          });
        }
      }
      request({
        url: this.uploadUrl,
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data",
        },
        data: this.buildUploadFormData(file),
      })
        .then((attachmentResp) => {
          this.fileList.push(attachmentResp);
        })
        .catch((err) => {
          this.$message.error(err || "文件上传失败");
        })
        .finally(() => {
          if (this.showLoading) {
            loading.close();
          }
        });
    },
    buildUploadFormData(file) {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", this.type);
      formData.append("dataKey", this.dataKey);
      formData.append("bizType", this.bizType);
      formData.append("isTemp", this.isTemp);
      return formData;
    },
  },
};
</script>

<style scoped lang="scss"></style>
